package io.github.wslxm.springbootplus2.starter.robot.api;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.lang.Dict;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import io.github.wslxm.springbootplus2.starter.robot.properties.WebhookProperties;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 飞书 群机器人
 *
 * @author wangsong
 * @date 2023/04/10
 */
public class FenShuApi {

    /**
     * 发送 Webhook 消息
     * @param webhookProperties
     * @param content
     */
    public static String sendMsg(WebhookProperties webhookProperties, String content) {
        String defaultAtUser = webhookProperties.getDefaultAtUser();
        if (defaultAtUser!=null && !"".equals(defaultAtUser)) {
            content += "\n";
            if ("@all".equals(webhookProperties.getDefaultAtUser())) {
                content += "<at user_id=\"all\">所有人</at>";
            } else {
                List<String> userIds = Arrays.asList(webhookProperties.getDefaultAtUser().split(","));
                for (String userId : userIds) {
                    content += "<at user_id=\"" + userId + "\"></at>";
                }
            }
        }
        // 加签
        long timestamp = System.currentTimeMillis() / 1000;
        String sign = genSign(webhookProperties.getSecret(), timestamp);
        // 拼接消息体
        Map<String, Object> paramMap = new HashMap<>(4);
        paramMap.put("timestamp", timestamp);
        paramMap.put("sign", sign);
        paramMap.put("msg_type", "text");
        paramMap.put("content", Dict.create().set("text", content));
        // 请求
        return HttpRequest.post(webhookProperties.getUrl()).
                header("Content-Type", "application/json;charset=utf-8").
                body(JSON.toJSONString(paramMap)).
                execute().body();
    }

    /**
     * 签名
     * @param secret 秘密
     * @param timestamp 时间戳
     * @return {@link String}
     * @throws NoSuchAlgorithmException 没有这样算法异常
     * @throws InvalidKeyException 无效关键例外
     */
    private static String genSign(String secret, long timestamp) {
        //把timestamp+"\n"+密钥当做签名字符串
        String stringToSign = timestamp + "\n" + secret;
        //使用HmacSHA256算法计算签名
        Mac mac = null;
        try {
            mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(stringToSign.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        byte[] signData = mac.doFinal(new byte[]{});
        return Base64Encoder.encode(signData);
    }
}
